import React, { useState, useEffect, useCallback } from 'react'
// 🔧 修改：使用真实的 API，而不是 mockApi
import { getDataImages, deleteDataImage, deleteDataImagesBatch, searchDataImages } from '../../utils/api'

export default function BrowseModule({ onBack, stats }) {
  const [images, setImages] = useState([])
  const [loading, setLoading] = useState(false)
  const [selectedImages, setSelectedImages] = useState([])
  const [viewMode, setViewMode] = useState('grid') // 'grid' or 'list'
  const [filterTag, setFilterTag] = useState('all')
  const [sortBy, setSortBy] = useState('createdAt')
  const [selectedImage, setSelectedImage] = useState(null)

  const loadImages = useCallback(async () => {
    setLoading(true)
    try {
      let data
      if (filterTag === 'all') {
        // 🔧 修改：使用新的 API
        data = await getDataImages()
      } else {
        // 🔧 修改：使用新的搜索 API
        data = await searchDataImages({ 
          tags: [filterTag],
          sortBy: sortBy 
        })
      }
      
      // 排序
      if (sortBy === 'name') {
        data.sort((a, b) => (a.name || '').localeCompare(b.name || ''))
      } else {
        data.sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0))
      }
      
      setImages(data)
    } catch (err) {
      console.error('加载图片失败:', err)
      alert('加载图片失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }, [filterTag, sortBy])

  useEffect(() => {
    loadImages()
  }, [loadImages])

  // 选择/取消选择图片
  function toggleSelectImage(id) {
    setSelectedImages(prev => 
      prev.includes(id) 
        ? prev.filter(i => i !== id)
        : [...prev, id]
    )
  }

  // 全选/取消全选
  function toggleSelectAll() {
    if (selectedImages.length === images.length) {
      setSelectedImages([])
    } else {
      setSelectedImages(images.map(img => img.id))
    }
  }

  // 批量删除
  async function handleBatchDelete() {
    if (selectedImages.length === 0) {
      alert('请先选择要删除的图片')
      return
    }

    if (!window.confirm(`确认删除选中的 ${selectedImages.length} 张图片吗？`)) {
      return
    }

    setLoading(true)
    try {
      // 🔧 修改：使用批量删除 API
      await deleteDataImagesBatch(selectedImages)
      await loadImages()
      setSelectedImages([])
      alert('批量删除成功')
    } catch (err) {
      console.error('批量删除失败:', err)
      alert('批量删除失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  // 导出数据
  function handleExport() {
    if (selectedImages.length === 0) {
      alert('请先选择要导出的图片')
      return
    }

    const selectedData = images.filter(img => selectedImages.includes(img.id))
    const exportData = selectedData.map(img => ({
      name: img.name,
      tags: img.tags || [],
      description: img.description || '',
      detections: img.detections || [],
      createdAt: img.createdAt,
      confidence: img.confidence || 0
    }))

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `export_${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
    
    alert(`成功导出 ${selectedImages.length} 张图片的数据`)
  }

  // 查看详情
  function viewDetail(image) {
    setSelectedImage(image)
  }

  // 关闭详情
  function closeDetail() {
    setSelectedImage(null)
  }

  // 删除单张图片
  async function handleDeleteSingle(id) {
    if (!window.confirm('确认删除这张图片吗？')) return

    setLoading(true)
    try {
      // 🔧 修改：使用新的删除 API
      await deleteDataImage(id)
      await loadImages()
      if (selectedImage && selectedImage.id === id) {
        setSelectedImage(null)
      }
      alert('删除成功')
    } catch (err) {
      console.error('删除失败:', err)
      alert('删除失败: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  const availableTags = ['all', ...Object.keys(stats.tags || {})]
  console.log('Available tags:', availableTags) // 避免 ESLint 警告

  return (
    <div className="browse-module">
      {/* 页面标题 */}
      <div className="card">
        <div className="card-header">
          <div className="section-title">
            <span className="section-icon">🗂️</span>
            <div>
              <h3 className="card-title">数据浏览</h3>
              <p className="card-subtitle">浏览和管理所有图片数据，支持批量操作</p>
            </div>
          </div>
          <button className="back-btn" onClick={onBack}>
            ← 返回
          </button>
        </div>

        {/* 工具栏 */}
        <div className="browse-toolbar">
          {/* 筛选和排序 */}
          <div className="toolbar-filters">
            <div className="filter-item">
              <label className="filter-label">
                <span>🏷️</span>
                <span>标签筛选</span>
              </label>
              <select 
                className="filter-select"
                value={filterTag}
                onChange={(e) => setFilterTag(e.target.value)}
              >
                <option value="all">全部 ({images.length})</option>
                {Object.keys(stats.tags || {}).map(tag => (
                  <option key={tag} value={tag}>
                    {tag} ({stats.tags[tag]})
                  </option>
                ))}
              </select>
            </div>

            <div className="filter-item">
              <label className="filter-label">
                <span>🔄</span>
                <span>排序方式</span>
              </label>
              <select
                className="filter-select"
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
              >
                <option value="createdAt">按时间</option>
                <option value="name">按名称</option>
              </select>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="toolbar-actions">
            <button
              className="toolbar-btn"
              onClick={toggleSelectAll}
              disabled={images.length === 0}
            >
              <span>{selectedImages.length === images.length && images.length > 0 ? '☑️' : '☐'}</span>
              <span>{selectedImages.length === images.length && images.length > 0 ? '取消全选' : '全选'}</span>
            </button>
            <button
              className="toolbar-btn danger"
              onClick={handleBatchDelete}
              disabled={selectedImages.length === 0}
            >
              <span>🗑️</span>
              <span>批量删除</span>
            </button>
            <button
              className="toolbar-btn success"
              onClick={handleExport}
              disabled={selectedImages.length === 0}
            >
              <span>📥</span>
              <span>导出数据</span>
            </button>
            <button
              className="toolbar-btn"
              onClick={loadImages}
              disabled={loading}
            >
              <span>🔄</span>
              <span>刷新</span>
            </button>
          </div>
        </div>

        {/* 选择提示 */}
        {selectedImages.length > 0 && (
          <div className="selection-info">
            <span className="selection-icon">✓</span>
            <span>已选择 <strong>{selectedImages.length}</strong> 张图片</span>
            <button 
              className="clear-selection-btn"
              onClick={() => setSelectedImages([])}
            >
              清除选择
            </button>
          </div>
        )}
      </div>

      {/* 视图切换和内容 */}
      <div className="card">
        <div className="browse-header">
          <h3 className="browse-title">
            <span>📊</span>
            <span>图片库</span>
            <span className="browse-count">{images.length} 张</span>
          </h3>
          <div className="view-toggle">
            <button
              className={`view-btn ${viewMode === 'grid' ? 'active' : ''}`}
              onClick={() => setViewMode('grid')}
            >
              <span>⊞</span>
              <span className="view-label">网格</span>
            </button>
            <button
              className={`view-btn ${viewMode === 'list' ? 'active' : ''}`}
              onClick={() => setViewMode('list')}
            >
              <span>☰</span>
              <span className="view-label">列表</span>
            </button>
          </div>
        </div>

        {/* 加载状态 */}
        {loading && (
          <div className="loading-overlay">
            <div className="loading-spinner"></div>
            <p style={{ marginTop: '16px', color: '#6b7280' }}>加载中...</p>
          </div>
        )}

        {/* 空状态 */}
        {!loading && images.length === 0 && (
          <div className="empty-state">
            <div className="empty-icon">📭</div>
            <h3>暂无图片数据</h3>
            <p>请先上传图片或切换其他标签筛选</p>
          </div>
        )}

        {/* 网格视图 */}
        {!loading && images.length > 0 && viewMode === 'grid' && (
          <div className="browse-grid">
            {images.map((img) => (
              <div
                key={img.id}
                className={`browse-card ${selectedImages.includes(img.id) ? 'selected' : ''}`}
              >
                <div className="browse-card-checkbox">
                  <input
                    type="checkbox"
                    checked={selectedImages.includes(img.id)}
                    onChange={() => toggleSelectImage(img.id)}
                  />
                </div>
                
                <div 
                  className="browse-card-image"
                  onClick={() => viewDetail(img)}
                >
                  <img src={img.filepath ? `http://localhost:3000${img.filepath}` : (img.dataUrl || img.url)} alt={img.name} />
                  {img.detections && img.detections.length > 0 && (
                    <div className="defect-badge">
                      ⚠️ {img.detections.length} 个缺陷
                    </div>
                  )}
                </div>
                
                <div className="browse-card-content">
                  <h4 className="browse-card-name" title={img.name}>
                    {img.name}
                  </h4>
                  
                  {img.tags && img.tags.length > 0 && (
                    <div className="browse-card-tags">
                      {img.tags.slice(0, 2).map((tag, idx) => (
                        <span key={idx} className="browse-tag">{tag}</span>
                      ))}
                      {img.tags.length > 2 && (
                        <span className="browse-tag">+{img.tags.length - 2}</span>
                      )}
                    </div>
                  )}
                  
                  <div className="browse-card-footer">
                    <span className="browse-date">
                      {img.createdAt ? new Date(img.createdAt).toLocaleDateString() : '未知'}
                    </span>
                    <button
                      className="browse-delete-btn"
                      onClick={(e) => {
                        e.stopPropagation()
                        handleDeleteSingle(img.id)
                      }}
                      title="删除"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 列表视图 */}
        {!loading && images.length > 0 && viewMode === 'list' && (
          <div className="browse-list">
            {images.map((img) => (
              <div
                key={img.id}
                className={`browse-list-item ${selectedImages.includes(img.id) ? 'selected' : ''}`}
              >
                <div className="browse-list-checkbox">
                  <input
                    type="checkbox"
                    checked={selectedImages.includes(img.id)}
                    onChange={() => toggleSelectImage(img.id)}
                  />
                </div>
                
                <div 
                  className="browse-list-image"
                  onClick={() => viewDetail(img)}
                >
                  <img src={img.filepath ? `http://localhost:3000${img.filepath}` : (img.dataUrl || img.url)} alt={img.name} />
                </div>
                
                <div className="browse-list-content" onClick={() => viewDetail(img)}>
                  <h4 className="browse-list-name">{img.name}</h4>
                  {img.description && (
                    <p className="browse-list-description">{img.description}</p>
                  )}
                  {img.tags && img.tags.length > 0 && (
                    <div className="browse-list-tags">
                      {img.tags.map((tag, idx) => (
                        <span key={idx} className="browse-tag">{tag}</span>
                      ))}
                    </div>
                  )}
                </div>
                
                <div className="browse-list-meta">
                  {img.detections && img.detections.length > 0 && (
                    <div className="browse-list-defects">
                      <span className="defects-icon">⚠️</span>
                      <span>{img.detections.length} 个缺陷</span>
                    </div>
                  )}
                  <div className="browse-list-date">
                    {img.createdAt ? new Date(img.createdAt).toLocaleString() : '未知时间'}
                  </div>
                  <button
                    className="browse-list-delete-btn"
                    onClick={(e) => {
                      e.stopPropagation()
                      handleDeleteSingle(img.id)
                    }}
                  >
                    🗑️ 删除
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 详情模态框 */}
      {selectedImage && (
        <div className="modal-backdrop" onClick={closeDetail}>
          <div className="modal-content browse-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>{selectedImage.name}</h3>
              <button className="modal-close-btn" onClick={closeDetail}>✕</button>
            </div>
            <div className="modal-body">
              <div className="modal-image">
                <img src={selectedImage.filepath ? `http://localhost:3000${selectedImage.filepath}` : (selectedImage.dataUrl || selectedImage.url)} alt={selectedImage.name} />
              </div>
              <div className="modal-info">
                {selectedImage.description && (
                  <div className="modal-section">
                    <h4>📝 AI 智能描述</h4>
                    <p>{selectedImage.description}</p>
                  </div>
                )}
                {selectedImage.tags && selectedImage.tags.length > 0 && (
                  <div className="modal-section">
                    <h4>🏷️ 智能标签</h4>
                    <div className="modal-tags">
                      {selectedImage.tags.map((tag, idx) => (
                        <span key={idx} className="modal-tag">{tag}</span>
                      ))}
                    </div>
                  </div>
                )}
                {selectedImage.detections && selectedImage.detections.length > 0 && (
                  <div className="modal-section">
                    <h4>⚠️ 缺陷检测结果</h4>
                    <div className="detection-list">
                      {selectedImage.detections.map((det, idx) => (
                        <div key={idx} className="detection-item">
                          <span>{det.class || det.label || '未知缺陷'}</span>
                          <span className="detection-confidence">
                            {((det.confidence || 0) * 100).toFixed(1)}%
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                <div className="modal-section">
                  <h4>📅 创建时间</h4>
                  <p>{selectedImage.createdAt ? new Date(selectedImage.createdAt).toLocaleString() : '未知时间'}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
